/** 5. 拆解搜索条件 */
<template>
  <div class="tear_container">
    <a-row :gutter="15">
      <a-col :span="10" class="source_site_col" :gutter="2">
        <a-row class="tear_condition_table_row">
          <a-col :span="24">
            <!-- 第一级：需要拆解的搜索条件选择表 -->
            <a-table
              :dataSource="step_data.tear_conditions"
              :columns="tb_columns.tear_conditions_tb_columns"
              :pagination="false"
              size="small"
              :rowClassName="
                (record, index) => (record.active ? 'dealing_row' : '')
              "
            >
              <template #bodyCell="{ record, column }">
                <template v-if="column.key === 'category_path'">
                  <a :href="record.category_url" target="_blank">{{
                    record.category_path
                  }}</a>
                </template>
                <template v-if="column.key === 'operation'">
                  <a
                    v-if="!record.status"
                    @click="on_handle_tear_condition(record)"
                    >处理</a
                  >
                  <a v-if="record.status === 1">重置</a>
                </template>
                <!-- <template v-if="column.key === 'status'">
                  <ACheckCircleFilled
                    style="color: red"
                    v-if="column.value === 1"
                  />
                  <ACloseCircleFilled style="color: green" v-else />
                </template> -->
              </template>
            </a-table>
          </a-col>
        </a-row>
        <a-row class="main_row" :gutter="[10, 0]" style="margin-top: 40px">
          <a-col :span="24">
            <a-row style="margin-bottom: 10px">
              <a-col :span="24">
                <h3>
                  {{ active_tear_condition?.category_path ?? "请选择" }}
                  搜索条件列表
                </h3>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <!-- 第二级：需要拆解的类目条件选择表 -->
                <a-table
                  :dataSource="active_tear_condition.options"
                  :columns="tb_columns.condition_options_tb_columns"
                  :pagination="{ pageSize: 10 }"
                  :rowClassName="
                    (record, index) => (record.active ? 'dealing_row' : '')
                  "
                >
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'image_url'">
                      <a-image
                        :width="64"
                        :src="record.image_url"
                        :preview="false"
                      />
                    </template>
                    <template v-if="column.key === 'operation'">
                      <a
                        @click="set_to_tearing_condition(record);"
                        >拆分</a
                      >
                    </template>
                  </template>
                </a-table>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-col>
      <a-col :span="14">
        <a-row
          style="padding: 12px; border: 1px solid #e8e8e8; border-radius: 5px"
        >
          <a-col :span="8">
            <a-space direction="vertical">
              <h3>待拆解选项图例</h3>
              <p>
                {{ to_teardown_option?.option_name ?? "请选择拆解条件选项" }}
              </p>
              <a-image :width="168" :src="to_teardown_option.image_url" />
            </a-space>
          </a-col>
          <!-- <a-divider type="vertical" />
          <a-col :span="8"> 111 </a-col> -->
        </a-row>
        <a-row :span="24">
          <a-tabs
            v-model:activeKey="active_tab_key"
            class="site_tabs"
            :destroyInactiveTabPane="true"
            @change="handleTabChange"
          >
            <!-- 第三级: 选择要拆解对应的目标站点 -->
            <a-tab-pane
              v-for="tear_site_map_item in available_site_map"
              :key="tear_site_map_item.site_code"
              :tab="tear_site_map_item.site_name"
              force-render
            >
              <div style="padding: 4px">
                <a-row>
                  <a-col :span="6"> <span>拆解目标类目:</span> </a-col>
                  <a-col :span="14">
                    <a-select
                      placeholder="请选择本类目的上级类目"
                      style="width: 100%"
                      v-model:value="selected_to_teardown_category_value"
                      :options="select_teardown_condition_options"
                      :dropdown-match-select-width="360"
                      @change="select_teardown_condition($event)"
                      size="small"
                    >
                    </a-select>
                  </a-col>
                  <a-col :span="4" style="text-align: right">
                    <a :href="selected_to_teardown_category_url" target="_blank"
                      >访问类目页</a
                    >
                  </a-col>
                </a-row>
              </div>
              <div>
                <a-space
                  :style="{
                    width: '100%',
                    display: 'flex',
                    justifyContent: 'space-between',
                  }"
                >
                  <h3 style="text-align: left">拆分搜索条件组合表</h3>
                  <!-- 拆分搜索条件组合表操作区 暂时留空 -->
                  <a-space :gutter="2">
                    <a-button
                      @click="
                        tear_target_condition_tb_ds.forEach((item) => {
                          item.is_show = !item.is_show;
                        })
                      "
                      >反选展示</a-button
                    >
                    <a-button
                      type="primary"
                      @click="
                        tear_target_condition_tb_ds.forEach((item) => {
                          item.is_active = !item.is_active;
                        })
                      "
                      >反选启用</a-button
                    >
                  </a-space>
                </a-space>
                <a-row>
                  <a-col :span="24">
                    <!-- 拆分搜索条件组合表 -->
                    <a-table
                      :dataSource="tear_target_condition_tb_ds"
                      :columns="tb_columns.condition_value_tb_columns"
                      :pagination="{ pageSize: 10 }"
                      :rowClassName="
                        (record, index) =>
                          record.is_deleted ? 'deleted-row' : ''
                      "
                      size="small"
                    >
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.key === 'condition_selector'">
                          <a-select
                            placeholder="选择匹配选项"
                            style="width: 100%"
                            v-model:value="record.condition_selector_value"
                            :options="
                              record.options.map((item) => ({
                                label: item.option_name,
                                value: item.option_value,
                              }))
                            "
                            :disabled="!record.is_active"
                            @change="
                              record.image_url = record.options.find(
                                (item) =>
                                  item.option_value ===
                                  record.condition_selector_value
                              ).image_url
                            "
                          >
                          </a-select>
                        </template>
                        <template v-if="column.key === 'condition_image'">
                          <a-image :width="64" :src="record.image_url" />
                        </template>
                        <template v-if="column.key === 'is_show'">
                          <a-switch
                            v-model:checked="record.is_show"
                            :disabled="!record.is_active"
                          />
                        </template>
                        <template v-if="column.key === 'is_active'">
                          <a-switch v-model:checked="record.is_active" />
                        </template>
                      </template>
                    </a-table>
                  </a-col>
                </a-row>
              </div>
            </a-tab-pane>
            <a-tab-pane key="default">
              <!-- 默认的占位面板 -->
              <p style="padding: 24px; color: #666">请先选择需要拆解的站点</p>
            </a-tab-pane>
          </a-tabs>
        </a-row>
      </a-col>
    </a-row>

    <a-space
      :style="{ width: '100%', display: 'flex', justifyContent: 'center' }"
    >
      <a-button @click="finish" type="primary">提交对齐</a-button>
    </a-space>
    <read-only-mask :enabled="step_data.read_only" />
  </div>
</template>

<script setup>
import { ref, onMounted, createVNode } from "vue";
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import {
  fetch_process_data,
  update_step_data,
  get_site_data,
  get_process_step_data,
  clone_condition_map_by_class,
  get_raw_condition_map,
  get_baseline_site_code,
} from "@/utils/selection";

const emit = defineEmits(["finish"]);

// 获取当前进度数据
const process_data = ref({});

// 步骤数据
const step_data = ref({
  read_only: false,
  tear_conditions: [],
});

// 待拆解的站点映射
const tear_site_map = ref({});

// 可用的站点映射
const available_site_map = ref({});

// 点击处理按钮: 设置当前处理的条件
const on_handle_tear_condition = (record) => {
  active_tear_condition.value = record;
  step_data.value.tear_conditions.forEach((item) => {
    item.active = false;
  });
  record.active = true;
  tear_target_condition_tb_ds.value = [];
  selected_to_teardown_category_value.value = '';
};

onMounted(async () => {
  // 获取当前进度数据
  process_data.value = await fetch_process_data();

  // 目标拆分条件表
  const target_tear_groups = clone_condition_map_by_class(
    process_data.value,
    "tear_group"
  );

  // 读取待拆解组的分类搜索条件映射表
  const temp_tear_groups = Object.values(
    get_raw_condition_map(process_data.value)
  ).flat();

  // 构建待拆解的站点映射数据
  temp_tear_groups.forEach((item) => {
    if (!tear_site_map.value[`${item.site_code}:${item.category_code}`]) {
      tear_site_map.value[`${item.site_code}:${item.category_code}`] = {
        site_name: item.site_name,
        site_code: item.site_code,
        site_url: "",
        site_conditions: [item],
      };
    } else {
      tear_site_map.value[
        `${item.site_code}:${item.category_code}`
      ].site_conditions.push(item);
    }
  });
  console.log(`output->temp_tear_groups`, temp_tear_groups);

  // 读取当前步骤数据
  const last_step_data =
    get_process_step_data(process_data.value, "TEARDOWN")?.data ?? null;
  if (last_step_data) {
    step_data.value = last_step_data;
    const last_tear_site_map = get_process_step_data(
      process_data.value,
      "TEARDOWN"
    )?.extra_data?.tear_site_map;
    // if (last_tear_site_map && Object.keys(last_tear_site_map).length > 0 && false) {  // 禁用缓存
    if (last_tear_site_map && Object.keys(last_tear_site_map).length > 0) {
      tear_site_map.value = last_tear_site_map;
    }
    // 从读取到的 target_tear_groups 补充 step_data 中缺少的站点数据 (处理新增拆解项的情况)
    target_tear_groups.forEach((item) => {
      if (
        !step_data.value.tear_conditions.find(
          (t) =>
            t.site_code === item.site_code &&
            t.condition_code === item.condition_code
        )
      ) {
        step_data.value.tear_conditions.push(item);
      }
    });
    message.success("读取过程数据成功");
  } else {
    step_data.value.tear_conditions = target_tear_groups;
  }

  // 默认激活第一个待拆解的条件
  if (step_data.value.tear_conditions.length > 0) {
    on_handle_tear_condition(step_data.value.tear_conditions[0]);
    if (active_tear_condition.value.options.length > 0) {
      set_to_tearing_condition(active_tear_condition.value.options[0])
    }
  }
});

// 完成步骤: 更新提交当前步骤数据
const finish = async () => {
  Modal.confirm({
    title: "即将提交对齐流程",
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
      "div",
      { style: "color:red;" },
      "提交后无法修改，是否继续？"
    ),
    async onOk() {
      message.info("正在提交数据，请稍后...");
      // 设置只读
      step_data.value.read_only = true;
      // 更新提交当前步骤数据
      if (
        await update_step_data(
          "TEARDOWN",
          process_data.value,
          step_data.value,
          { tear_site_map: tear_site_map.value }
        )
      ) {
        // 跳转到下一步
        emit("finish");
      }
    },
    onCancel() {
      console.log("Modal Canceled");
    },
    class: "test",
  });
};

// 第二级: 激活的待分解的类目条件数据
const active_tear_condition = ref({});

// 待拆分的条件选项数据
const to_teardown_option = ref({});

// 当前激活的 tab 面板
const active_tab_key = ref("default");

// 点击拆分按钮: 设置待拆分的条件
const set_to_tearing_condition = (record) => {
  console.log("set_to_tearing_condition ->", record);

  // 生成可用的站点映射 每个站点只能拆分到本站点或者基准站点
  available_site_map.value = Object.values(tear_site_map.value)
    .filter((item) => {
      return (
        item.site_code === active_tear_condition.value.site_code ||
        item.site_code === get_baseline_site_code(process_data.value)
      );
    }) // 去重
    .filter(
      (item, index, self) =>
        self.findIndex(
          (t) =>
            t.site_code === item.site_code &&
            t.category_code === item.category_code
        ) === index
    );

  to_teardown_option.value = record;
  active_tab_key.value = active_tear_condition.value.site_code;
  reset_teardown_combination(active_tear_condition.value.site_code);

  active_tear_condition.value.options.forEach((item) => {
    item.active = false;
  });
  record.active = true;
};

// 第三级: 拆分条件组合数据
const tear_target_condition_tb_ds = ref([]);

// 选择拆分目标类目
const select_teardown_condition = (value) => {
  console.log("select_teardown_condition ->", value);
  const [site_code, category_code, category_path] = value.split(":");
  // 从待拆解的数据中找到对应的条件选项
  function filter_condition(_site_code, _category_code, _category_path) {
    const res = tear_site_map.value[
      `${_site_code}:${_category_code}`
    ].site_conditions.filter((item) => item.category_path === _category_path);
    console.log("filter_condition ->", res);
    return res;
  }
  // 检查是否已经存在拆分条件组合
  if (!to_teardown_option.value.teared_target_condition_group) {
    to_teardown_option.value.teared_target_condition_group = {};
  }
  // 如果不存在已经存在的站点拆分组合 则从搜索条件选项中拷贝出对应的条件组合
  if (!to_teardown_option.value.teared_target_condition_group[site_code]) {
    to_teardown_option.value.teared_target_condition_group[site_code] = [];
  }

  console.log(
    `output->to_teardown_option.value.teared_target_condition_group`,
    to_teardown_option.value.teared_target_condition_group
  );

  if (
    // 如果不存在则拷贝一份选择项
    !to_teardown_option.value.teared_target_condition_group[site_code].find(
      (item) => {
        return (
          item.site_code === site_code && item.category_code === category_code
        );
      }
    )
  ) {
    to_teardown_option.value.teared_target_condition_group[site_code] =
      JSON.parse(
        JSON.stringify(
          filter_condition(site_code, category_code, category_path)
        )
      );
  }

  // 设置待拆分的条件选项表内容
  tear_target_condition_tb_ds.value =
    to_teardown_option.value.teared_target_condition_group[site_code].filter(
      (item) => {
        // console.log(`output->item`,item)
        try {
          return (
            item.site_code === site_code && item.category_code === category_code
          );
        } catch (err) {
          console.error("select_teardown_condition ->", err);
        }
      }
    );
  console.log(
    "tear_target_condition_tb_ds ->",
    tear_target_condition_tb_ds.value
  );

  // 找到选中的待拆分类目链接 临时解决方案
  try {
    selected_to_teardown_category_url.value =
      tear_target_condition_tb_ds.value[0].category_url;
  } catch (err) {
    console.error("select_teardown_condition ->", err);
    selected_to_teardown_category_url.value = "";
  }
};

const select_teardown_condition_options = ref([]);

// 拆分站点页面切换
const handleTabChange = (site_code) => {
  reset_teardown_combination(site_code);
};

// 选中的待拆分类目
const selected_to_teardown_category_value = ref("");
// 选中的待拆分类目链接
const selected_to_teardown_category_url = ref("");

// 重置拆分条件组合并更新拆分条件选项
const reset_teardown_combination = (site_code) => {
  console.log("reset_teardown_combination ->", site_code);
  console.log("to_teardown_option ->", to_teardown_option.value);
  // 检查是否有激活的待拆分项
  if (!to_teardown_option.value.option_name) {
    message.error("请先选择需要拆分的条件");
    active_tab_key.value = "default";
    return;
  }
  console.log(`output->tear_site_map.value`, tear_site_map.value);
  // select_teardown_condition_options.value = tear_site_map.value[
  //   `${site_code}:${active_tear_condition.value.category_code}`
  // ].site_conditions
  //   // 过滤出当前站点的所有类目
  //   .filter((item) => item.site_code === site_code)
  //   // 将类目转换为下拉选项
  //   .map((item) => ({
  //     label: `${item.category_path}`,
  //     value: `${item.site_code}:${item.category_path}`,
  //   }))
  //   // 过滤去重
  //   .filter(
  //     (item, index, self) =>
  //       self.findIndex((t) => t.value === item.value) === index
  //   );
  select_teardown_condition_options.value = Object.values(tear_site_map.value)
    .filter((item) => item.site_code === site_code)
    .map((item) => ({
      label: `${item.site_conditions[0].category_path}`,
      value: `${item.site_code}:${item.site_conditions[0].category_code}:${item.site_conditions[0].category_path}`,
    }));
  // 清空拆分搜索条件组合表
  tear_target_condition_tb_ds.value = [];
  // 清空选中的待拆分类目
  selected_to_teardown_category_value.value = "";
};

// 表格列配置
const tb_columns = ref({
  tear_conditions_tb_columns: [
    {
      title: "站点",
      dataIndex: "site_code",
      key: "site_code",
    },
    {
      title: "类目导航",
      dataIndex: "category_path",
      key: "category_path",
    },
    {
      title: "类目名",
      dataIndex: "category_name",
      key: "category_name",
    },
    {
      title: "搜索条件/码",
      dataIndex: "condition_name",
      key: "condition_name",
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
    },
    // {
    //   title: "状态",
    //   dataIndex: "status",
    //   key: "status",
    // },
  ],
  condition_options_tb_columns: [
    {
      title: "选项图例",
      dataIndex: "image_url",
      key: "image_url",
    },
    {
      title: "选项名",
      dataIndex: "option_name",
      key: "option_name",
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
    },
  ],
  condition_value_tb_columns: [
    {
      title: "选项名",
      dataIndex: "condition_name",
      key: "condition_name",
    },
    {
      title: "选项选择器",
      dataIndex: "condition_selector",
      key: "condition_selector",
    },
    {
      title: "图例",
      dataIndex: "condition_image",
      key: "condition_image",
    },
    {
      title: "是否展示",
      dataIndex: "is_show",
      key: "is_show",
    },
    {
      title: "是否启用",
      dataIndex: "is_active",
      key: "is_active",
    },
  ],
});
</script>

<script>
/* eslint-disable */
import {
  CheckCircleFilled,
  CloseCircleFilled,
  PlusOutlined,
} from "@ant-design/icons-vue";
import {
  Row,
  Col,
  Table,
  Button,
  Image,
  Modal,
  ImagePreviewGroup,
  Tabs,
  Select,
  SelectOption,
  TabPane,
  List,
  ListItem,
  ListItemMeta,
  Popconfirm,
  Switch,
  Space,
  Divider,
} from "ant-design-vue";
import ReadOnlyMask from "../commons/ReadOnlyMask.vue";
export default {
  components: {
    ARow: Row,
    ACol: Col,
    ATabs: Tabs,
    ATabPane: TabPane,
    AButton: Button,
    AModal: Modal,
    AImage: Image,
    ATable: Table,
    ASelect: Select,
    AList: List,
    AListItem: ListItem,
    AListItemMeta: ListItemMeta,
    AImagePreviewGroup: ImagePreviewGroup,
    ASelectOption: SelectOption,
    PlusOutlined: PlusOutlined,
    ACheckCircleFilled: CheckCircleFilled,
    ACloseCircleFilled: CloseCircleFilled,
    APopconfirm: Popconfirm,
    ASwitch: Switch,
    ADivider: Divider,
    ASpace: Space,
  },
};
</script>

<style lang="scss">
.tear_container {
  margin-top: 10px;
  padding: 0px 100px;

  .source_site_col {
    padding: 10px;
    border: 1px solid #e8e8e8;
    border-radius: 5px;
    height: 100%;
  }

  .tear_condition_table_row {
    height: auto;
  }

  .main_row {
    margin-top: 10px;
  }

  .match_image_col {
    text-align: center;
  }

  .site_tabs {
    border: 1px solid #e8e8e8;
    padding: 0 10px;
    border-radius: 5px;
    width: 100%;
    height: 100%;
  }

  .model_class {
    text-align: center;
  }

  .deleted-row {
    display: none;
  }

  .dealing_row {
    background-color: rgba(255, 166, 0, 0.125);

    .ant-table-cell-row-hover {
      background-color: rgba(255, 166, 0, 0.25);
    }
  }
}
</style>
